package com.ruoyi.bussiness.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;

import com.alibaba.fastjson.JSONPath;
import com.alibaba.nls.client.AccessToken;
import com.alibaba.nls.client.protocol.InputFormatEnum;
import com.alibaba.nls.client.protocol.NlsClient;
import com.alibaba.nls.client.protocol.SampleRateEnum;
import com.alibaba.nls.client.protocol.asr.SpeechTranscriber;
import com.alibaba.nls.client.protocol.asr.SpeechTranscriberListener;
import com.alibaba.nls.client.protocol.asr.SpeechTranscriberResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 此示例演示了：
 * ASR实时识别API调用。
 * 动态获取token。获取Token具体操作，请参见：https://help.aliyun.com/document_detail/450514.html
 * 通过本地模拟实时流发送。
 * 识别耗时计算。
 * @author 12290
 */
public class NlsClientRequest {
//    @Value("${audio.appkey}")
//    private String appKey;
//    @Value("${audio.id}")
//    private String id;
//    @Value("${audio.secret}")
//    private String secret;
//    @Value("${audio.url}")
//    private String url;


    private  final String appKey = "8UwmGy93dk4I9ffi";
    private  final String id = "LTAI5tJCvkH8c5Z36ZFQz4AT";
    private final String secret = "z4orPXT2o790yog7GpGqIXJQAJqKOx";

    private final String url = "https://nls-gateway-cn-shanghai.aliyuncs.com/stream/v1/asr";

    private String token = "";


    private static String result = "";
    private static final Logger logger = LoggerFactory.getLogger(NlsClientRequest.class);

    public NlsClientRequest() throws IOException {
        //应用全局创建一个NlsClient实例，默认服务地址为阿里云线上服务地址。
        //获取token，实际使用时注意在accessToken.getExpireTime()过期前再次获取。
        AccessToken accessToken = new AccessToken(id, secret);
        accessToken.apply();
        token = accessToken.getToken();
    }

    public String process(String fileName) throws Exception {

        /**
         * 设置HTTPS RESTful POST请求：
         * 1.使用HTTPS协议。
         * 2.语音识别服务域名：nls-gateway-cn-shanghai.aliyuncs.com。
         * 3.语音识别接口请求路径：/stream/v1/asr。
         * 4.设置必选请求参数：appkey、format、sample_rate。
         * 5.设置可选请求参数：enable_punctuation_prediction、enable_inverse_text_normalization、enable_voice_detection。
         */
        String format = "pcm";
        int sampleRate = 16000;
        boolean enablePunctuationPrediction = true;
        boolean enableInverseTextNormalization = true;
        boolean enableVoiceDetection = false;

        String request = url;
        request = request + "?appkey=" + appKey;
        request = request + "&format=" + format;
        request = request + "&sample_rate=" + sampleRate;
        if (enablePunctuationPrediction) {
            request = request + "&enable_punctuation_prediction=" + true;
        }
        if (enableInverseTextNormalization) {
            request = request + "&enable_inverse_text_normalization=" + true;
        }
        if (enableVoiceDetection) {
            request = request + "&enable_voice_detection=" + true;
        }

        logger.info("Request: " + request);

        /**
         * 设置HTTPS头部字段：
         * 1.鉴权参数。
         * 2.Content-Type：application/octet-stream。
         */
        HashMap<String, String> headers = new HashMap<String, String>();
        headers.put("X-NLS-Token", this.token);
        headers.put("Content-Type", "application/octet-stream");

        /**
         * 发送HTTPS POST请求，返回服务端的响应。
         */
        String response = HttpUtil.sendPostFile(request, headers, fileName);

        if (response != null) {
            return JSONPath.read(response, "result").toString();
        }
        else {
            throw new Exception("识别失败");
        }

    }
}